<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #canvas {
            border: 1px solid black;
        }
    </style>
</head>
<body>

<canvas id="canvas" width="600px" height="400px"></canvas>

<script>

    const cvs = document.querySelector("#canvas")
    const ctx = cvs.getContext('2d')

    const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',
        'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

    drawCode()

    function drawCode() {

        ctx.width = 600
        ctx.height = 400

        ctx.fillStyle = 'orange'
        ctx.fillRect(0, 0, 160, 60)

        let str = ""
        for (let i = 0; i < 4; i++) {
            const index = getRandom(0, 35)
            str += arr[index]

        }
        console.log('生成的验证码是:', str)

        ctx.beginPath()
        ctx.font = "22px sans-serif"
        ctx.fillStyle = "#333"
        ctx.fillText(str, 40, 40, 160)
    }


    cvs.addEventListener('click',()=>{
        drawCode()
    })

    // 计算指定范围内的随机函数
    function getRandom(min, max) {
        return Math.floor(Math.random() * (max - min + 1) + min)
    }
</script>
</body>
</html>